﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using DynamicViewModel;

namespace Sample.StackOverflow
{
    public class UsersViewModel : DynamicViewModel.DynamicViewModel
    {
        private readonly BackgroundWorker _backgroundWorker;

        public UsersViewModel()
        {
            This.IsBusy = false;
            SearchCommand = new RelayCommand(SearchHandler);

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork +=
                (s, e) =>
                    {
                        var uriString =
                            string.Format("http://api.stackoverflow.com/1.1/users?filter={0}", e.Argument);

                        var webRequest = (HttpWebRequest) WebRequest.Create(uriString);
                        webRequest.AutomaticDecompression = DecompressionMethods.GZip;

                        var response = webRequest.GetResponse();
                        var responseStream = response.GetResponseStream();
                        if (responseStream == null)
                            return;

                        using (var streamReader = new StreamReader(responseStream))
                        {
                            var json = streamReader.ReadToEnd();
                            dynamic obj = DynamicViewModelFactory.Create(json);

                            e.Result = obj.users;
                        }
                    };
            _backgroundWorker.RunWorkerCompleted +=
                (s, e) =>
                    {
                        This.IsBusy = false;
                        SetSearchResults((List<DynamicViewModel.DynamicViewModel>) e.Result);
                    };
        }

        private void SearchHandler()
        {
            SetSearchResults(new List<DynamicViewModel.DynamicViewModel>(Enumerable.Empty<DynamicViewModel.DynamicViewModel>()));
            This.IsBusy = true;
            _backgroundWorker.RunWorkerAsync(SearchFilter);
        }

        private void SetSearchResults(List<DynamicViewModel.DynamicViewModel> list)
        {
            SearchResults = list;
            RaisePropertyChanged("SearchResults");
        }

        public string SearchFilter { get; set; }
        public List<DynamicViewModel.DynamicViewModel> SearchResults { get; private set; }
        public ICommand SearchCommand { get; private set; }
    }
}
